package a66weding.com.jiehuntong.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import org.xutils.x;
import java.util.ArrayList;
import java.util.List;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.hotel.shop.HomeProductdetailActivity;
import a66weding.com.jiehuntong.adapter.ShopAdapter;
import a66weding.com.jiehuntong.adapter.StoreMyListAdapter;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CaseBean;
import a66weding.com.jiehuntong.beans.CasesDetail;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HomeBotomListBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeShopDetBean;
import a66weding.com.jiehuntong.beans.StoreDetailGuess;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.User;
import a66weding.com.jiehuntong.beans.WXbean;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.ImageOptionsUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.view.CircleImageView;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;
import a66weding.com.jiehuntong.widgets.MyListView;
import a66weding.com.jiehuntong.widgets.NoScrollGridView;
import a66weding.com.jiehuntong.widgets.dialog.MyRedheartDialog;
import a66weding.com.jiehuntong.widgets.scrollreflash.PullToLoadScroll;
import a66weding.com.jiehuntong.widgets.scrollreflash.PullToLoadScrollLissener;

/**
 * Created by admin on 2016/8/2.
 * 作用：案例详情
 */
public class StoreDetailsActivity extends Activity implements OnNetResultListener,PullToLoadScrollLissener , AdapterView.OnItemClickListener,View.OnClickListener{
    public static String STOREDETAILSACTIVITY = "StoreDetailsActivity";
    private CaseBean.DataBean  bean;
    private  int casesID;
    private PullToLoadScroll mSc;
    private  View homeView;
    private NoScrollGridView gridView;
    private boolean isDownRefresh = true;
    private MyListView lv;
    private TextView title;
    private CircleImageView  circularImage;
    private List<HomeBotomListBean.DataBean> homeBotomListBeanList;
    private  TextView view_home_jeishoa;
    private TextView view_home_fensi;
    private TextView view_home_jinru;
    private ShopAdapter adapter;
    private CircleImageView midle_circularImage;
    private ImageView mNoIv;
    private ImageView mShowIv;
    private int memberID;
    private boolean isLogin;
    private User user;
    private User.DataBean userBean;
    private int BusinessID;
    private MyRedheartDialog myDialog;
    private int BASE_REQUEST_LOGIN_CODE=9000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_details);
        findViewById(R.id.title_tv).setVisibility(View.INVISIBLE);
        bean = (CaseBean.DataBean) getIntent().getSerializableExtra(STOREDETAILSACTIVITY);
        casesID = bean.getI_Id();
        pcategory = bean.getI_CategoryId();
        initView();
        initData();
        getData(1);
        getNetData();
    }
    private void initView(){
        homeBotomListBeanList = new ArrayList<>();
        mSc = (PullToLoadScroll) findViewById(R.id.scrollView_pl);
        homeView = View.inflate(this,R.layout.view_home,null);
        mSc.setContentView(homeView);
        mSc.setCall(this);
        gridView= (NoScrollGridView) homeView.findViewById(R.id.HomeView_Lv);
        gridView.setOnItemClickListener(this);
        adapter = new ShopAdapter(this,null);
        gridView.setAdapter(adapter);
        title = (TextView) homeView.findViewById(R.id.view_home_title);
        mNoIv = (ImageView) homeView.findViewById(R.id.cate_attention);
        mShowIv = (ImageView) homeView.findViewById(R.id.cate_attention_show);
        lv = (MyListView) findViewById(R.id.view_home_lv);
        circularImage = (CircleImageView) findViewById(R.id.view_home_icon);
        view_home_jeishoa = (TextView) findViewById(R.id.view_home_jeishoa);
        view_home_fensi = (TextView) findViewById(R.id.view_home_fensi);
        view_home_jinru = (TextView) findViewById(R.id.view_home_jinru);
        view_home_jinru.setOnClickListener(this);
        midle_circularImage = (CircleImageView) findViewById(R.id.view_home_icon_below);
    }
    private void initData(){
        x.image().bind(midle_circularImage,bean.getBusiness().getNvc_Logo(),ImageOptionsUtil.getOptions292_700());
        view_home_jeishoa.setText(bean.getBusiness().getNvc_StoreName());
        view_home_fensi.setText("已有"+bean.getBusiness().getBusinessMemberCount()+"个粉丝");
        isLogin  = ((GlobalApplication)getApplication()).isLogin();
        if(isLogin) {
            user = DataWareHourse.getInstance().getmUser();
            userBean = user.getData().get(0);
            memberID=userBean.getI_Id();
        }
    }
    private CasesDetail casebean;
    private StoreDetailGuess gussbean;
    @Override
    protected void onResume() {
        super.onResume();
        RefrashCall();
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Tools.dismissWaitDialog();
        Object data = sucessbean.getData();
        if(data instanceof CasesDetail){
            casebean= (CasesDetail) data;
            switch (casebean.getResCode()){
                case "0000":
                    // 如果请求成功再设置点击事件
                    mNoIv.setOnClickListener(this);
                    mShowIv.setOnClickListener(this);
                    String[] str = casebean.getData().getNvc_Content().split(",");
                    StoreMyListAdapter storeMyListAdapter = new StoreMyListAdapter(this,str);
                    lv.setAdapter(storeMyListAdapter);
                    title.setText(casebean.getData().getBusiness().getNvc_StoreName());
                    x.image().bind(circularImage,casebean.getData().getBusiness().getNvc_Logo(),ImageOptionsUtil.getOptions316_720());
                    BusinessID = casebean.getData().getI_BusinessId();

                    // 店铺详情接口
                    if (isLogin) {  // 如果登陆
                        meInitData(casebean.getData().getBusiness().getNvc_No(),("" + memberID));
                    } else {        // 如果没有登录
                        meInitData(casebean.getData().getBusiness().getNvc_No() ,"0");
                    }

                    break;
            }
        }
        if (data instanceof  MeShopDetBean) {
            MeShopDetBean meShopDetBean = (MeShopDetBean) data;
            if ("0000".equals(meShopDetBean.getResCode())) {
                if (meShopDetBean.getData().isCollectionStare()) {// 如果已经关注
                    mNoIv.setVisibility(View.GONE);
                    mShowIv.setVisibility(View.VISIBLE);
                } else {
                    mNoIv.setVisibility(View.VISIBLE);
                    mShowIv.setVisibility(View.GONE);
                }
            }
        }

        if (data instanceof CommonResultBean) {     // 关注
            CommonResultBean commonResultBean = (CommonResultBean) data;
            if ("0000".equals(commonResultBean.getResCode())) {     // 关注成功
                myDialog = new MyRedheartDialog(this,"关注成功!");
                myDialog.show();
                mNoIv.setVisibility(View.GONE);
                mShowIv.setVisibility(View.VISIBLE);
            }
        }
        if (data instanceof WXbean){        //取消关注
            WXbean wXbean = (WXbean) data;
            if ("0000".equals(wXbean.getResCode())) {    //取消关注成功
                myDialog = new MyRedheartDialog(this,"成功取消关注!");
                myDialog.show();
                mNoIv.setVisibility(View.VISIBLE);
                mShowIv.setVisibility(View.GONE);
            }
        }
        if (data instanceof  StoreDetailGuess){
            mSc.commplate();
            gussbean = (StoreDetailGuess) data;
            switch (gussbean.getResCode()){
                case "0000":
                    if (isDownRefresh){
                        adapter.clear();
                    }
                    adapter.append(gussbean.getData());
                    mSc.invalidate();
                    break;
                case "0003":
                    //数据为空;
                    mSc.commplate();
                    break;
            }

        }
        changeData(gussbean.getData());
    }
    @Override
    public void onError(ErrorBean errorBean) {

    }
    private void getNetData(){
        Tools.showDialog(this);
        String url = Url.GET_CASESDETAIL+"casesID="+casesID;
        HttpRequestBean bottomListRequestBean = new HttpRequestBean(RequestCode.GETREQUEST,url,this, CasesDetail.class,RequestCode.GET_CASESDETAIL);
        HttpHandleUtil.executeCommonGet(this,bottomListRequestBean);
    }
    private int pageIndex = 1;
    private int pcategory = 0;
    /**
     * GET WeddingMobileApi/get_CasesProductListLike?Token={Token}&pageIndex={pageIndex}&PCategory={PCategory}//分类ID
     * 案例详细页面 猜你喜欢
     * @param pageIndex
     */
    private void getData(int pageIndex){
        String url = Url.GET_CASESPRODUCTLISTLIKE+"pageIndex="+pageIndex+"&PCategory="+pcategory;
        HttpRequestBean bottomListRequestBean = new HttpRequestBean(RequestCode.GETREQUEST,url,this, StoreDetailGuess.class,RequestCode.GET_CASESPRODUCTLISTLIKE);
        HttpHandleUtil.executeCommonGet(this,bottomListRequestBean);
    }

    /**
     * 关注接口
     * POST WeddingMobileApi/post_BusinessMemberCreate?Token={Token}&MemberID={MemberID}&BusinessID={BusinessID}
     * +关注 关注店铺
     */
    private void attention(){
        String url =  Url.POST_BUSINESSMEMBERCREATE+"&MemberID="+memberID+"&BusinessID="+BusinessID;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                this, CommonResultBean.class, RequestCode.POST_BUSINESSMEMBERCREATE);
        HttpHandleUtil.executeCommonPost(this,httpRequestBean);
    }

    /**
     * POST WeddingMobileApi/post_CancelBusinessMember?Token={Token}&MemberID={MemberID}&BusinessID={BusinessID}
     * 取消关注
     */
    private void unsubscribe(){
        String url =  Url.POST_CANCELBUSINESSMEMBER + "&MemberID="+memberID+"&BusinessID="+BusinessID;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                this, WXbean.class, RequestCode.POST_BUSINESSMEMBERCREATE);
        HttpHandleUtil.executeCommonPost(this,httpRequestBean);
    }
    /**
     * POST WeddingMobileApi/post_CancelBusinessMember?Token={Token}&MemberID={MemberID}&BusinessID={BusinessID}
     * 店铺详情的网络请求
     */
    private void meInitData(String getNvcNo,String memberID){
        // 发起网络请求
        String url = Url.GET_BUSINESSDETAIL_NO+"&nvcNo="+getNvcNo+"&memberID="+memberID;
        HttpRequestBean RequestBean = new HttpRequestBean(RequestCode.GETREQUEST,url,this,
                MeShopDetBean.class,RequestCode.GET_CASESDETAIL);
        HttpHandleUtil.executeCommonGet(this,RequestBean);
    }
    @Override
    public void RefrashCall() {
        isDownRefresh = true;
        pageIndex = 1;
        getNetData();
        getData(1);
    }

    @Override
    public void LoadCall() {
        isDownRefresh = false;
        ++pageIndex ;
        getData(pageIndex);
    }

    /**
     * 点击item事件;
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this,HomeProductdetailActivity.class);
        intent.putExtra("productId",homeBotomListBeanList.get(position).getI_Id());
        startActivity(intent);
    }

    public void back(View view){
        finish();
    }
    private void changeData(List<StoreDetailGuess.DataBean> dataBeen){
        if (isDownRefresh) {
            homeBotomListBeanList.clear();
        }
        HomeBotomListBean.DataBean.BusinessBean businessBean = new  HomeBotomListBean.DataBean.BusinessBean();
        businessBean.setNvc_StoreName(casebean.getData().getBusiness().getNvc_StoreName());
        businessBean.setNvc_Address(casebean.getData().getBusiness().getNvc_Address());
        for (int i = 0; i < dataBeen.size(); i++) {
            HomeBotomListBean.DataBean homeBean = new HomeBotomListBean.DataBean();
            homeBean.setI_Collections(dataBeen.get(i).getI_Collections());
            homeBean.setI_Category(dataBeen.get(i).getI_Category());
            homeBean.setDm_Price(dataBeen.get(i).getDm_Price());
            homeBean.setDm_ShopPrice(dataBeen.get(i).getDm_ShopPrice());
            homeBean.setNvc_PicMain(dataBeen.get(i).getNvc_PicMain());
            homeBean.setNvc_Name(dataBeen.get(i).getNvc_Name());
            homeBean.setBusiness(businessBean);
            homeBean.setI_Id(dataBeen.get(i).getI_Id());
            homeBotomListBeanList.add(homeBean);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //进入店铺;
            case R.id.view_home_jinru:
                Intent intent = new Intent(this,ShopDetailsActivity.class);
                intent.putExtra("nvc_num",""+casebean.getData().getBusiness().getNvc_No());
                intent.putExtra("BusinessID", casebean.getData().getI_BusinessId());
                startActivityForResult(intent,1);
                break;
            case R.id.cate_attention:   //未关注状态,点击关注
                if (isLogin) {          // 如果登陆
                    attention();
                } else {
                    showLoginDialog(this,BASE_REQUEST_LOGIN_CODE+1);
                }

                break;
            case R.id.cate_attention_show: //关注状态,点击取消关注
                if (isLogin) {
                    unsubscribe();
                } else {
                    showLoginDialog(this,BASE_REQUEST_LOGIN_CODE+2);
                }
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
          if (resultCode==LoginActivity.LOGIN_OK){
              isLogin  = ((GlobalApplication)getApplication()).isLogin();
              if(isLogin) {
                  user = DataWareHourse.getInstance().getmUser();
                  if (user!=null){
                      userBean = user.getData().get(0);
                      memberID=userBean.getI_Id();
                  }
              }
          }
        if (requestCode==(BASE_REQUEST_LOGIN_CODE+1)&&resultCode==LoginActivity.LOGIN_OK){
            initData();
            attention();
        }else if (requestCode==(BASE_REQUEST_LOGIN_CODE+2)&&resultCode==LoginActivity.LOGIN_OK){
            initData();
            unsubscribe();
        }
    }

    public  void showLoginDialog(Context context, final int code) {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(context, "亲，需要登录哦~",  "去登录", "取消",R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                Intent intent = new Intent(StoreDetailsActivity.this, LoginActivity.class);
                startActivityForResult(intent,code);
                confirmDialog.dismiss();
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }


}
